from flask import Flask, request, jsonify
from flask_cors import CORS  # 导入 CORS 模块
import pymysql

app = Flask(__name__)

# 允许所有域访问
CORS(app)

# 数据库连接
def get_db_connection():
    conn = pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='mydatabase',
        charset='utf8bm4'
    )
    return conn

# 注册用户
@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    email = data['email']
    password = data['password']

    conn = get_db_connection()
    cursor = conn.cursor()

    cursor.execute("INSERT INTO data (email, password) VALUES (%s, %s)", (email, password))
    conn.commit()
    conn.close()

    return jsonify({"message": "注册成功"}), 201

# 登录用户
@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    email = data['email']
    password = data['password']

    conn = get_db_connection()
    cursor = conn.cursor()

    cursor.execute("SELECT * FROM data WHERE email = %s AND password = %s", (email, password))
    user = cursor.fetchone()
    conn.close()

    if user:
        return jsonify({"message": "登录成功"}), 200
    else:
        return jsonify({"message": "无效的凭证"}), 401

if __name__ == "__main__":
    app.run(debug=True)
